package utils

import (
	"encoding/json"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

//公共方法

//++++++++++ begin
/*
生成一个随机字符串(数字+字母)
每次RandomString()生成字符串再2次拼接
n:生成随机数个数的平方
*/
func CreateRandomString(n int) string {
	var str strings.Builder
	for i := 0; i < n; i++ {
		str.WriteString(RandomString(n))
	}
	return str.String()
}

/*
随机生成字母+数字
n:生成随机数个数
*/
func RandomString(n int) string {
	letterAndNum := "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ23456789"
	r := rand.New(rand.NewSource(time.Now().Unix())) //不重复引进time包
	str := make([]byte, n)
	for i := range str {
		str[i] = letterAndNum[r.Intn(len(letterAndNum))] //不重复引进time包
		// str[i] = letterAndNum[rand.Intn(len(letterAndNum))] //可能重复
	}
	return string(str)
}

//++++++++++ end

/*
拼接字符串
可变参数
*/
func ConcatWithStringsBuilder(args ...string) string {
	var str strings.Builder
	for i := range args {
		str.WriteString(args[i])
	}
	return str.String()
}

/*
[断言->是否改成泛型？？？]把某个类型转换成字符串string
return string
*/
func ToString(value interface{}) string {
	var str string
	if value == nil {
		return str
	}
	// vt := value.(type)
	switch value.(type) {
	case float64:
		ft := value.(float64)
		str = strconv.FormatFloat(ft, 'f', -1, 64)
	case float32:
		ft := value.(float32)
		str = strconv.FormatFloat(float64(ft), 'f', -1, 64)
	case int:
		it := value.(int)
		str = strconv.Itoa(it)
	case uint:
		it := value.(uint)
		str = strconv.Itoa(int(it))
	case int8:
		it := value.(int8)
		str = strconv.Itoa(int(it))
	case uint8:
		it := value.(uint8)
		str = strconv.Itoa(int(it))
	case int16:
		it := value.(int16)
		str = strconv.Itoa(int(it))
	case uint16:
		it := value.(uint16)
		str = strconv.Itoa(int(it))
	case int32:
		it := value.(int32)
		str = strconv.Itoa(int(it))
	case uint32:
		it := value.(uint32)
		str = strconv.Itoa(int(it))
	case int64:
		it := value.(int64)
		str = strconv.FormatInt(it, 10)
	case uint64:
		it := value.(uint64)
		str = strconv.FormatUint(it, 10)
	case string:
		str = value.(string)
	case []byte:
		str = string(value.([]byte))
	default:
		newValue, _ := json.Marshal(value)
		str = string(newValue)
	}

	return str
}

// 数组||切片拆分成多少份
func SplitSliceAndArray(arr []int, num int) [][]int {
	max := len(arr)
	if max < num {
		return nil
	}
	var retArr = make([][]int, 0)
	quantity := max / num
	end := 0
	for i := 1; i <= num; i++ {
		qu := i * quantity
		if i != num {
			retArr = append(retArr, arr[i-1+end:qu])
		} else {
			retArr = append(retArr, arr[i-1+end:])
		}
		end = qu - i
	}
	return retArr
}
